const app = getApp()
const api = app.globalData.api
Page({
    data: {
        result: [],
        total: 0,
        count: 0,
        page: 1,
        pageAll: 0,
        where: '',
        sortShow: false,
        sortArray: [],
        popNum: 0,
        popShow: false,
        popArray: {}
    },
    list: async function (param = {}, page = 1) {
        const url = '?cla=saleSendOrder&fun=material&page=' + page
        let res = await api.curlPost(url, param)
        if (res.code === 1) {
            const page = res.data.page
            this.setData({
                page: page.pageNow,
                pageAll: page.pageAll,
                sortArray: res.data.orderBy,
                result: res.data.result,
                where: api.arrayToJson(param)
            })
        }
    },
    seleMaterial: async function (e) {
        let obj = e.currentTarget.dataset
        if (obj.material) {
            wx.navigateTo({
                url: 'materialDetail?data=' + obj.material
            })
        }
    },
    initOther: async function () {
        const saleData = wx.getStorageSync('saleData')
        this.setData({
            total: api.total(saleData, ['price', 'num']),
            count: api.count(saleData),
        })
    },
    onLoad: async function (options) {
        await this.list()
        await this.initOther()
    },
    onSearch: async function (e) {
        await this.list({
            'wd': e.detail
        })
    },
    addInStock: function () {
        wx.navigateTo({
            url: 'add'
        })
    },
    // 上拉加载
    onReachBottom() {
        if (!this.loading && this.data.page < this.data.pageAll) {
            const page = parseInt(this.data.page),
                param = api.jsonToArray(this.data.where)
            this.list(param, page + 1)
        }
    },
    showHide(obj, bool = true) {
        const field = obj.currentTarget.dataset.target
        if (field) {
            this.setData({
                [field]: bool
            })
        }
    },
    // 排序
    sortFun(obj) {
        let array = obj.detail,
            that = this
        if (array.act === '确定') {
            that.list({
                orderBy: array.val
            })
        }
        that.setData({
            sortShow: false
        })
    },
    // 显示当前已选
    showMaterial() {
        const saleData = wx.getStorageSync('saleData')
        this.setData({
            popShow: true,
            popNum: Object.keys(saleData).length,
            popArray: saleData
        })
    },
    onPopClose() {
        this.setData({popShow: false});
    },
    // 删除
    delMaterial(obj) {
        const id = obj.currentTarget.dataset.materialid
        let saleData = wx.getStorageSync('saleData')
        delete saleData[id]
        this.setData({
            popNum: Object.keys(saleData).length,
            popArray: saleData
        })
        wx.setStorageSync('saleData', saleData)
    }
});